package subscription

import (
	"context"
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/common/simplecopier"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/common/constants"
	subscriptionDto "git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/dto/subscription"
	common2 "git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/repository/common"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/repository/subscription"
	businessOpportunityPb "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/business_opportunity"
	commonPb "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/common"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/service/base/user/user_service"
	"git.myscrm.cn/golang/stark/v4"
	"strings"
)

type subscriptionService struct {
	subscriptionRepo subscription.SubscriptionRepositoryIface
	optionRepo       common2.OptionRepositoryIface
	userRepo         user_service.UserRepositoryIface
}

// NewSubscriptionService
// 创建构造函数
func NewSubscriptionService(
	subscriptionRepo subscription.SubscriptionRepositoryIface,
	optionRepo common2.OptionRepositoryIface,
	userRepo user_service.UserRepositoryIface,
) SubscriptionServiceIface {
	return &subscriptionService{
		subscriptionRepo: subscriptionRepo,
		optionRepo:       optionRepo,
		userRepo:         userRepo,
	}
}

/*
func (s *subscriptionService) ApplyCron(ctx context.Context, params *subscriptionDto.EmptyRequest) (interface{}, error) {
	return s.subscriptionRepo.ApplyCron(ctx, params)
}*/

func (s *subscriptionService) GetRadarSubscriptionConfig(ctx context.Context, request *subscriptionDto.GetRadarSubscriptionConfigRequest) (*subscriptionDto.GetRadarSubscriptionConfigResponse, error) {
	requestPb := &businessOpportunityPb.GetRadarSubscriptionConfigRequest{}
	simplecopier.CopyToStruct(requestPb, request)
	//获取用户union_id
	globalUserId := authorize.GetGlobalUserId(ctx)
	userInfo, err := s.userRepo.GetUserInfo(ctx, &user_service.GetUserInfoParams{
		GlobalUId: globalUserId,
	})
	if err != nil {
		stark.Logger.Errorf(ctx, "获取用户数据异常,err%s", err.Error())
	}
	if userInfo != nil && userInfo.UserInfo.MpUnionId != "" {
		requestPb.UnionId = userInfo.UserInfo.MpUnionId
	}

	resPb, err := s.subscriptionRepo.GetRadarSubscriptionConfig(ctx, requestPb)
	if err != nil {
		stark.Logger.Error(ctx, "获取订阅配置，失败:", err)
		return nil, err
	}
	res := &subscriptionDto.GetRadarSubscriptionConfigResponse{}
	res.Id = resPb.Id
	res.IsLandOpen = resPb.IsLandOpen
	res.IsSaleOpen = resPb.IsSaleOpen
	res.IsBuildingOpen = resPb.IsBuildingOpen
	res.AreaCode = s.getStringArr(resPb.AreaCode)
	res.ProjectKeyword = s.getStringArr(resPb.ProjectKeyword)
	res.BidKeywordExclude = s.getStringArr(resPb.BidKeywordExclude)
	res.WinbidKeyword = s.getStringArr(resPb.WinbidKeyword)
	res.BidKeyword = s.getStringArr(resPb.BidKeyword)
	res.SaleType = s.getStringArr(resPb.SaleType)
	res.BuildingType = s.getStringArr(resPb.BuildingType)
	res.LandUsage = s.getStringArr(resPb.LandUsage)
	return res, nil

}

func (s *subscriptionService) getStringArr(data string) []string {
	if data != "" {
		return strings.Split(data, ",")
	} else {
		return make([]string, 0)
	}
}

func (s *subscriptionService) SaveRadarSubscriptionConfig(ctx context.Context, request *subscriptionDto.SaveRadarSubscriptionConfigRequest) (*subscriptionDto.SaveRadarSubscriptionConfigResponse, error) {
	requestPb := &businessOpportunityPb.SaveRadarSubscriptionConfigRequest{}
	requestPb.Id = request.Id
	requestPb.IsSaleOpen = request.IsSaleOpen
	requestPb.IsLandOpen = request.IsLandOpen
	requestPb.IsBuildingOpen = request.IsBuildingOpen
	requestPb.SaleType = strings.Join(request.SaleType, ",")
	requestPb.LandUsage = strings.Join(request.LandUsage, ",")
	requestPb.BuildingType = strings.Join(request.BuildingType, ",")
	requestPb.BidKeyword = strings.Join(request.BidKeyword, ",")
	requestPb.WinbidKeyword = strings.Join(request.WinbidKeyword, ",")
	requestPb.BidKeywordExclude = strings.Join(request.BidKeywordExclude, ",")
	requestPb.AreaCode = strings.Join(request.AreaCode, ",")
	requestPb.ProjectKeyword = strings.Join(request.ProjectKeyword, ",")
	resPb, err := s.subscriptionRepo.SaveRadarSubscriptionConfig(ctx, requestPb)
	if err != nil {
		stark.Logger.Error(ctx, "保存线索雷达订阅，失败:", err)
	}
	res := &subscriptionDto.SaveRadarSubscriptionConfigResponse{}
	simplecopier.CopyToStruct(res, resPb)
	return res, nil
}

func (s *subscriptionService) GetSubscriptionPushConfig(ctx context.Context, request *subscriptionDto.GetSubscriptionPushConfigRequest) (*subscriptionDto.GetSubscriptionPushConfigResponse, error) {
	requestPb := &businessOpportunityPb.GetSubscriptionPushConfigRequest{}
	simplecopier.CopyToStruct(requestPb, request)
	resPb, err := s.subscriptionRepo.GetSubscriptionPushConfig(ctx, requestPb)
	if err != nil {
		stark.Logger.Error(ctx, "获取推送配置，失败:", err)
	}
	res := &subscriptionDto.GetSubscriptionPushConfigResponse{}
	errCopy := simplecopier.CopyToStruct(res, resPb)
	if errCopy != nil {
		stark.Logger.Error(ctx, "结构体转换,err:%s", errCopy.Error())
	}
	return res, nil
}

func (s *subscriptionService) SaveSubscriptionPushConfig(ctx context.Context, request *subscriptionDto.SaveSubscriptionPushConfigRequest) (*subscriptionDto.SaveSubscriptionPushConfigResponse, error) {
	requestPb := &businessOpportunityPb.SaveSubscriptionPushConfigRequest{}
	simplecopier.CopyToStruct(requestPb, request)
	resPb, err := s.subscriptionRepo.SaveSubscriptionPushConfig(ctx, requestPb)
	if err != nil {
		stark.Logger.Error(ctx, "保存推送配置，失败:", err)
	}
	res := &subscriptionDto.SaveSubscriptionPushConfigResponse{}
	simplecopier.CopyToStruct(res, resPb)
	return res, nil
}

func (s *subscriptionService) GetWxQrCode(ctx context.Context, request *subscriptionDto.GetWxQrCodeRequest, globalUserId string) (*subscriptionDto.GetWxQrCodeResponse, error) {
	userInfo, err := s.userRepo.GetUserInfo(ctx, &user_service.GetUserInfoParams{
		GlobalUId: globalUserId,
	})
	if err != nil {

	}
	requestPb := &businessOpportunityPb.GetWxQrCodeRequest{}
	if userInfo != nil && userInfo.UserInfo.MpUnionId != "" {
		requestPb.UnionId = userInfo.UserInfo.MpUnionId
	}

	simplecopier.CopyToStruct(requestPb, request)
	resPb, err := s.subscriptionRepo.GetWxQrCode(ctx, requestPb)
	if err != nil {
		stark.Logger.Error(ctx, "获取二维码，失败:", err)
	}
	res := &subscriptionDto.GetWxQrCodeResponse{}
	simplecopier.CopyToStruct(res, resPb)
	return res, nil
}

func (s *subscriptionService) GetBindStatus(ctx context.Context, sceneId string) (*subscriptionDto.GetBindStatusResponse, error) {
	requestPb := &businessOpportunityPb.GetBindStatusRequest{}
	requestPb.SceneId = sceneId
	resPb, err := s.subscriptionRepo.GetBindStatus(ctx, requestPb)
	if err != nil {
		stark.Logger.Error(ctx, "获取绑定状态，失败:", err)
	}
	res := &subscriptionDto.GetBindStatusResponse{}
	simplecopier.CopyToStruct(res, resPb)
	return res, nil
}

func (s *subscriptionService) BindOpenIdByCard(ctx context.Context, request *subscriptionDto.BindOpenIdByCardRequest) (*subscriptionDto.BindOpenIdByCardResponse, error) {
	requestPb := &businessOpportunityPb.BindOpenIdByCardRequest{
		YcgOpenid: request.YcgOpenId,
	}
	resPb, err := s.subscriptionRepo.BindOpenIdByCard(ctx, requestPb)
	if err != nil {
		stark.Logger.Errorf(ctx, "绑定ycg_openid，失败:%s", err.Error())
	}
	res := &subscriptionDto.BindOpenIdByCardResponse{
		IsNew: resPb.IsNew,
	}
	return res, nil
}

func (s *subscriptionService) GetRadarList(ctx context.Context, request *subscriptionDto.GetRadarListRequest) (*subscriptionDto.GetRadarListResponse, error) {
	if len(request.AreaCodes) == 0 {
		//如果用户没有输入省市地区，默认带入用户有权益的省市
		resp, err := s.optionRepo.RadarAreaOption(ctx, &commonPb.GetRadarAreaOptionRequest{})
		if err != nil {
			return nil, err
		}
		if resp != nil {
			for _, option := range resp.Options {
				request.AreaCodes = append(request.AreaCodes, option.AreaCode)
			}
		}
	}

	result, err := s.subscriptionRepo.GetRadarList(ctx, &businessOpportunityPb.GetRadarListRequest{
		AreaCodes:  request.AreaCodes,
		OpptyType:  request.OpptyType,
		StartTime:  request.StartTime,
		EndTime:    request.EndTime,
		Page:       request.Page,
		PageSize:   request.PageSize,
		FromDevice: constants.FromDeviceClueMini,
	})
	if err != nil {
		return nil, err
	}

	resp := &subscriptionDto.GetRadarListResponse{
		Total:    result.Total,
		NewTotal: result.NewTotal,
		MaxNum:   2000, // 后续改动的话，可以做成Apollo配置
		List:     []*subscriptionDto.RadarOpptyItem{},
	}
	for _, item := range result.List {
		respItem := &subscriptionDto.RadarOpptyItem{
			Uid:                     item.Uid,
			OpptyType:               item.OpptyType,
			BidSource:               item.BidSource,
			Title:                   item.Title,
			DeveloperName:           item.DeveloperName,
			DeveloperOrganizingCode: item.DeveloperOrganizingCode,
			PublishDate:             item.PublishDate,
			TakeLandDate:            item.TakeLandDate,
			OpeningDate:             item.OpeningDate,
			ProjectPlanBeginDate:    item.ProjectPlanBeginDate,
			ProjectRealityBeginDate: item.ProjectRealityBeginDate,
			ProjectPlanEndDate:      item.ProjectPlanEndDate,
			ProjectRealityEndDate:   item.ProjectRealityEndDate,
			OpptyStatus:             item.OpptyStatus,
			IsPriceGtAvg:            item.IsPriceGtAvg,
			IsNew:                   item.IsNew,
			ContactNum:              item.ContactNum,
			Label:                   item.Label,
			Province:                item.Province,
			City:                    item.City,
			ProvinceCode:            item.ProvinceCode,
			CityCode:                item.CityCode,
		}
		for _, supplier := range item.Suppliers {
			respItem.Suppliers = append(respItem.Suppliers, &subscriptionDto.SupplierItem{
				SupplierName:           supplier.SupplierName,
				SupplierOrganizingCode: supplier.SupplierOrganizingCode,
			})
		}
		resp.List = append(resp.List, respItem)
	}
	return resp, nil
}

func (s *subscriptionService) GetRadarPreCount(ctx context.Context, request *subscriptionDto.GetRadarPreCountRequest) (*subscriptionDto.GetRadarPreCountResponse, error) {
	result, err := s.subscriptionRepo.GetRadarPreCount(ctx, &businessOpportunityPb.GetRadarPreCountRequest{
		AreaCodes:         request.AreaCode,
		BidKeyword:        request.BidKeyword,
		WinbidKeyword:     request.WinbidKeyword,
		BidKeywordExclude: request.BidKeywordExclude,
		IsLandOpen:        request.IsLandOpen,
		LandUsage:         request.LandUsage,
		IsBuildingOpen:    request.IsBuildingOpen,
		BuildingType:      request.BuildingType,
		IsSaleOpen:        request.IsSaleOpen,
		SaleType:          request.SaleType,
		ProjectKeyword:    request.ProjectKeyword,
	})
	if err != nil {
		return nil, err
	}

	resp := &subscriptionDto.GetRadarPreCountResponse{
		MaxNum: 2000,
	}
	resp.Total = result.Total
	return resp, nil
}
